package com.sihai.ehr.web.action.contract;

import com.sihai.core.LimitedList;
import com.sihai.core.beans.BeanInject;
import com.sihai.ehr.model.biz.ContractSign;
import com.sihai.ehr.model.biz.ContractSignRt;
import com.sihai.ehr.model.biz.ContractSignRtt;
import com.sihai.ehr.model.biz.ContractSignZz;
import com.sihai.ehr.model.biz.Duty;
import com.sihai.ehr.model.biz.EmployeeinfoWork;
import com.sihai.ehr.service.ContractService;
import com.sihai.ehr.service.DutyService;
import com.sihai.ehr.service.EmployeeService;
import com.sihai.ehr.utils.EHRConfig;
import com.sihai.ehr.web.action.EHRAction;
import com.sihai.ehr.web.pojo.ContractSignViewPojo;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import javax.servlet.http.HttpServletResponse;

import java.io.*;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Results({ @Result(name = "list", location = "contract_person_view.jsp"),
		@Result(name = "main", location = "contract_main.jsp"),
		@Result(name = "print", location = "contract_sign.jsp") })
public class ContractAction extends EHRAction {

	@BeanInject
	private ContractService contractService;
	@BeanInject
	private DutyService dutyService;

	/**
	 * 员工信息服务
	 */
	@BeanInject
	private EmployeeService employeeService;

	private LimitedList<ContractSignViewPojo> viewPojos;
	private ContractSign sign;
	private ContractSignZz signZz;
	private ContractSignRt signRt;
	private ContractSignRtt signRtt;
	private List<Duty> duties;
	private String templateName;

	private Long dutyId;// 职务
	private int month;// 月份

	private Long id;
	private Long signId;
	private EmployeeinfoWork work;

	// 合同人员查看
	@Action("/contract/contPersonView_bak")
	@Override
	public String execute() throws Exception {
		listAction = "/contract/contPerson_list.xhtml";
		listTitle = "合同人员查看";

		return "main";
	}

	// 合同人员查看列表
	@Action("/contract/contPerson_list")
	public String list() throws Exception {
		duties = dutyService.searchDuty(organizationId, null, null); // TODO 待修改

		viewPojos = contractService.findContractSignList(organizationId,
				dutyId, month, createLimit(), createSorter());
		// 分页
		this.paging(viewPojos);
		this.setPageUrl("/contract/conPerson_list.xhtml");
		return "list";
	}

	/**
	 * 获取合同模板
	 * 
	 * @return
	 * @throws Exception
	 */
	// @Action(value = "/contract/contract_template", results = { @Result(name =
	// "success", type = "freemarker", location =
	// "/WEB-INF/pages/templates/${templateName}") })
	@Action(value = "/contract/contract_template", results = { @Result(name = "success", location = "/WEB-INF/pages/templates/${templateName}") })
	public String queryContractSignTemplate() throws Exception {
		Long employeeId = NumberUtils.createLong(getParameter("employId"));
		Long versionId = NumberUtils.createLong(getParameter("versionId"));
		templateName = getParameter("contract_template");
		// 传过来的模板不存在,读默认的模板
		if (!EHRConfig.templates.contains(templateName)) {
			templateName = EHRConfig.templates.get(0);
		}
		if (StringUtils.isNotBlank(templateName) && employeeId > 0) {
			// 获取员工合同Model对象
			if (StringUtils.equals("contract_template1.jsp", templateName)) {
				sign = contractService.getContractSignByEmployeeId(employeeId,
						versionId);
			} else if (StringUtils.equals("contract_template2.jsp",
					templateName)) {
				signZz = contractService.getContractSignZzByEmployeeId(
						employeeId, versionId);
			} else if (StringUtils.equals("contract_template3.jsp",
					templateName)) {
				signRt = contractService.getContractSignRtByEmployeeId(
						employeeId, versionId);
			} else if (StringUtils.equals("contract_template4.jsp",
					templateName)) {
				signRtt = contractService.getContractSignRttByEmployeeId(
						employeeId, versionId);
			}
			// templateName += (sign == null ? "_empty.ftl" : ".ftl");
		}
		return SUCCESS;
	}

	@Action(value = "/contract/print")
	public String contractPrint() throws Exception {
		work = employeeService.getEmployeeinfoWork(id);
		sign = contractService.getContractSign(signId);
		return "print";
	}

	@Action(value = "/contract/generateContractdoc")
	public String generateContractDoc() throws Exception {
		boolean isSign = (sign != null && sign.getId() != null);
		boolean isSignZz = (signZz != null && signZz.getId() != null);
		if (isSign == false && isSignZz == false) {
			return NONE;
		}

		// added by henry that handle the old contract @{
		boolean isSignRetire = (signRt != null && signRt.getId() != null);
		boolean isSignRtt = (signRtt != null && signRtt.getId() != null);
		if (isSign == false && isSignRetire == false && isSignRtt == false) {
			return NONE;
		}
		// added by henry @}
		String path = ServletActionContext.getRequest().getSession()
				.getServletContext().getRealPath("/");// 项目根目录
		String docPath = String.format("%s\\%s", path, "download");
		String templatePath = String.format("%s\\%s", path,
				"WEB-INF\\pages\\templates\\contractTemplate.doc");// 合同模板路径
		if (isSignZz) {
			templatePath = String.format("%s\\%s", path,
					"WEB-INF\\pages\\templates\\contractTemplateZz.doc");// 樟州合同模板路径
		}
		if (isSignRetire) {
			templatePath = String.format("%s\\%s", path,
					"WEB-INF\\pages\\templates\\contractTemplateRt.doc");// 退休人员合同模板路径
		}
		if (isSignRtt) {
			templatePath = String.format("%s\\%s", path,
					"WEB-INF\\pages\\templates\\contractTemplateRtt.doc");// 退休人员合同模板路径
		}

		FileInputStream in = new FileInputStream(new File(templatePath));
		HWPFDocument document = new HWPFDocument(in);

		Map<String, String> map = null;
		if (isSign) {
			map = getReplaceMap(sign.getId()); // 需要替换的键值对
		}
		if (isSignZz) {
			map = getReplaceMapZz(signZz.getId());
		}

		if (isSignRetire) {
			map = getReplaceMapRt(signRt.getId());
		}
		
		if(isSignRtt){
			map = getReplaceMapRtt(signRtt.getId());
		}
		// 替换读取到的word模板内容的指定字段
		Range range = document.getRange();
		for (Map.Entry<String, String> entry : map.entrySet()) {
			range.replaceText(entry.getKey(), entry.getValue());
			String temp = range.text();
		}
		String text = document.getDocumentText();
		// System.out.println(text);

		// -----------------写文件
		ByteArrayOutputStream ostream = new ByteArrayOutputStream();
		String fileName = "" + System.currentTimeMillis();
		fileName += ".doc";
		String tempFile = docPath + "\\" + fileName;
		FileOutputStream out = new FileOutputStream(tempFile, true);
		document.write(ostream);
		// 输出字节流
		out.write(ostream.toByteArray());
		out.close();
		ostream.close();

		File file = new File(tempFile);
		String downLoadName = "劳动合同-" + map.get("staffName") + ".doc";
		HttpServletResponse rs = ServletActionContext.getResponse();
		rs.setContentType("application/vsd.ms-word");
		rs.setHeader("Content-Disposition", "attachment;filename="
				+ new String(downLoadName.getBytes("UTF-8"), "ISO_8859_1"));
		// rs.setHeader("Content-Length", "");
		IOUtils.copy(new FileInputStream(file), rs.getOutputStream());

		if (file.exists()) // 删除生成的临时文件
			file.delete();
		return NONE;
	}

	public String download(String fileName, String realPath) throws Exception {
		return NONE;
	}

	private Map<String, String> getReplaceMap(long signId) {
		sign = contractService.getContractSign(signId);
		Map<String, String> map = new HashMap<String, String>();
		map.put("companyName", sign.getCompanyName());// 甲方
		map.put("companyType", sign.getCompHabitude());// 单位性质
		map.put("principal", sign.getPrincipal());// 法人代表
		map.put("companyAddress", sign.getComAddress());// 单位地址
		map.put("staffName", sign.getName()); // 员工姓名
		map.put("staffCensus", sign.getCensus());// 户籍所在地
		map.put("staffAddress", sign.getAddress());// 现居住地址
		map.put("staffIdcard", sign.getIdcard());// 身份证
		map.put("staffOtherCard", sign.getIdcardOther());// 其它有效证件号码
		map.put("workAddress", sign.getWork_place());// 工作地点
		map.put("dutyName", sign.getDuty().getDutyName());// 职务
		map.put("contractType", sign.getContractType());// 合同类型
		map.put("itemContent", sign.getItemContent());// 完成(生产工作)
		map.put("manHaur", sign.getManHaur());// 工时制度
		map.put("payType", sign.getPayType());// 工资标准形式
		map.put("probationerShippay", sign.getProbationerShippay());// 试用期工资
		map.put("formalPay", sign.getFormalPay());// 转正后工资
		map.put("payDate", String.valueOf(sign.getPayDate()));// 发工资日
		map.put("paydateBegin", String.valueOf(sign.getPaydateBegin())); // 上个月/当月(开始时间)
		map.put("paydateEnd", String.valueOf(sign.getPaydateEnd())); // 上个月/当月(结束时间)
		if (sign.getPieceRate() != null)
			map.put("pieceRate", String.valueOf(sign.getPieceRate()));// 计件定额
		else
			map.put("pieceRate", "/");// 计件定额
		if (sign.getPieceRatePay() != null)
			map.put("pieceRatePay", String.valueOf(sign.getPieceRatePay()));// 计件单价
		else
			map.put("pieceRatePay", "/");// 计件单价
		if (sign.getPaying() != null)
			map.put("paying", String.valueOf(sign.getPaying()));// 双方另行约定工资按以下支付形式
		else
			map.put("paying", "/");// 双方另行约定工资按以下支付形式
		if (sign.getOvertimeBase() != null)
			map.put("overtimeBase", String.valueOf(sign.getOvertimeBase()));// 加班加点工资的计算基数
		else
			map.put("overtimeBase", "/");// 加班加点工资的计算基数
		if ("1".equals(sign.getContractType())) {
			if (sign.getBeginDate() != null) {
				Calendar cal = Calendar.getInstance();
				cal.setTime(sign.getBeginDate());
				map.put("startYear1", String.valueOf(cal.get(1)));
				map.put("startMonth1", String.valueOf(cal.get(2)));
				map.put("startDay1", String.valueOf(cal.get(5)));
				map.put("syq1", sign.getProbationership());
				map.put("startYear2", "/");
				map.put("startMonth2", "/");
				map.put("startDay2", "/");
				map.put("syq2", "/");
			}
			if (sign.getEndDate() != null) {
				Calendar cal = Calendar.getInstance();
				cal.setTime(sign.getBeginDate());
				map.put("endYear", String.valueOf(cal.get(1)));
				map.put("endMonth", String.valueOf(cal.get(2)));
				map.put("endDay", String.valueOf(cal.get(5)));

			}
		} else if ("2".equals(sign.getContractType())) {
			if (sign.getBeginDate() != null) {
				Calendar cal = Calendar.getInstance();
				cal.setTime(sign.getBeginDate());
				map.put("startYear2", String.valueOf(cal.get(1)));
				map.put("startMonth2", String.valueOf(cal.get(2)));
				map.put("startDay2", String.valueOf(cal.get(5)));
				map.put("syq2", sign.getProbationership());

				map.put("startYear1", "/");
				map.put("startMonth1", "/");
				map.put("startDay1", "/");
				map.put("syq1", "/");
				map.put("endYear", "/");
				map.put("endMonth", "/");
				map.put("endDay", "/");
			}
		} else {
			map.put("startYear1", "/");
			map.put("startMonth1", "/");
			map.put("startDay1", "/");
			map.put("syq1", "/");
			map.put("endYear", "/");
			map.put("endMonth", "/");
			map.put("endDay", "/");

			map.put("startYear2", "/");
			map.put("startMonth2", "/");
			map.put("startDay2", "/");
			map.put("syq2", "/");
		}

		return map;
	}

	// 生成樟州合同需替换的文本
	private Map<String, String> getReplaceMapZz(long signZzId) {
		signZz = contractService.getContractSignZz(signZzId);
		Map<String, String> map = new HashMap<String, String>();
		map.put("staffName", signZz.getName()); // 员工姓名
		map.put("companyName", signZz.getCompanyName());
		map.put("name", signZz.getName());
		map.put("comAddress", signZz.getAddress());
		map.put("sex", signZz.getSex());
		map.put("principal", signZz.getPrincipal());// 法人代表
		map.put("birth", signZz.getBirth());
		map.put("comPhone", signZz.getComPhone());
		map.put("address", signZz.getAddress());
		map.put("census", signZz.getCensus());
		map.put("idcard", signZz.getIdcard());
		map.put("work_place", signZz.getWork_place());
		map.put("dutyName", signZz.getDuty().getDutyName());
		map.put("contractType", signZz.getContractType());
		if ("1".equals(signZz.getContractType())) {
			map.put("beginDateYear", signZz.getBeginDateYear() + "");
			map.put("beginDateMonth", signZz.getBeginDateMonth() + "");
			map.put("beginDateDay", signZz.getBeginDateDay() + "");
			map.put("beginDateYear2", "/");
			map.put("beginDateMonth2", "/");
			map.put("beginDateDay2", "/");
			map.put("syqStartDateYear", signZz.getSyqStartDateYear() + "");
			map.put("syqStartDateMonth", signZz.getSyqStartDateYear() + "");
			map.put("syqStartDateDay", signZz.getSyqStartDateYear() + "");
			map.put("syqStartDateYear2", "/");
			map.put("syqStartDateMonth2", "/");
			map.put("syqStartDateDay2", "/");
			map.put("endDateYear", signZz.getEndDateYear() + "");
			map.put("endDateMonth", signZz.getEndDateMonth() + "");
			map.put("endDateDay", signZz.getEndDateDay() + "");
			map.put("syqEndDateYear", signZz.getEndDateYear() + "");
			map.put("syqEndDateMonth", signZz.getEndDateMonth() + "");
			map.put("syqEndDateDay", signZz.getEndDateDay() + "");
			map.put("syqEndDateYear2", "/");
			map.put("syqEndDateMonth2", "/");
			map.put("syqEndDateDay2", "/");
		} else if ("2".equals(signZz.getContractType())) {
			map.put("beginDateYear2", signZz.getBeginDateYear() + "");
			map.put("beginDateMonth2", signZz.getBeginDateMonth() + "");
			map.put("beginDateDay2", signZz.getBeginDateDay() + "");
			map.put("beginDateYear", "/");
			map.put("beginDateMonth", "/");
			map.put("beginDateDay", "/");
		} else if ("3".equals(signZz.getContractType())) {
			map.put("syqStartDateYear2", signZz.getSyqStartDateYear() + "");
			map.put("syqStartDateMonth2", signZz.getSyqStartDateYear() + "");
			map.put("syqStartDateDay2", signZz.getSyqStartDateYear() + "");
			map.put("syqStartDateYear", "/");
			map.put("syqStartDateMonth", "/");
			map.put("syqStartDateDay", "/");
		}
		map.put("taskName", signZz.getTaskName());
		map.put("syqDays", signZz.getSyqDays());
		map.put("manHaur", signZz.getManHaur());
		map.put("amount", signZz.getAmount());
		map.put("quality", signZz.getQuality());
		map.put("payType", signZz.getPayType());
		map.put("syqSalary", signZz.getSyqSalary());
		map.put("partName1", signZz.getPartName1_());
		map.put("partName2", signZz.getPartName2_());
		map.put("partName3", signZz.getPartName3_());
		map.put("partSalary1", signZz.getPartSalary1_());
		map.put("partSalary2", signZz.getPartSalary2_());
		map.put("partSalary3", signZz.getPartSalary3_());
		map.put("pieceRatePay", signZz.getPieceRatePay() == null ? "" : signZz
				.getPieceRatePay().longValue() + "");
		map.put("payOther", signZz.getPayOther());
		map.put("payDate", signZz.getPayDate() + "");
		map.put("trainTreaty", signZz.getTrainTreaty_());
		map.put("businessTreaty", signZz.getBusinessTreaty_());
		map.put("welfareTreaty", signZz.getWelfareTreaty_());
		map.put("otherTreaty", signZz.getOtherTreaty_());

		return map;
	}

	// 生成退休人员合同需替换的文本
	private Map<String, String> getReplaceMapRt(long signRtId) {
		signRt = contractService.getContractSignRt(signRtId);
		Map<String, String> map = new HashMap<String, String>();
		map.put("staffName", signRt.getName()); // 员工姓名
		map.put("companyName", signRt.getCompanyName());
		map.put("name", signRt.getName());
		map.put("work_place", signRt.getWork_place());
		map.put("dutyName", signRt.getDuty().getDutyName());
		map.put("beginDateYear", signRt.getBeginDateYear() + "");
		map.put("beginDateMonth", signRt.getBeginDateMonth() + "");
		map.put("beginDateDay", signRt.getBeginDateDay() + "");
		map.put("endDateYear", signRt.getEndDateYear() + "");
		map.put("endDateMonth", signRt.getEndDateMonth() + "");
		map.put("endDateDay", signRt.getEndDateDay() + "");
		map.put("payType", signRt.getPayType());
		map.put("pieceRatePay", signRt.getPieceRatePay() == null ? "" : signRt
				.getPieceRatePay().longValue() + "");
		map.put("fullAward", signRt.getFullAward());
		map.put("baseSalary", signRt.getBaseSalary());
		map.put("dutyAllowance", signRt.getDutyAllowance());
		map.put("paymentDate", signRt.getPaymentDate() + "");
		

		return map;
	}
	
	// 生成退休人员合同二模块需替换的文本
	private Map<String, String> getReplaceMapRtt(long signRttId) {
		signRtt = contractService.getContractSignRtt(signRttId);
		Map<String, String> map = new HashMap<String, String>();
		map.put("staffName", signRtt.getName()); // 员工姓名
		map.put("companyName", signRtt.getCompanyName());
		map.put("name", signRtt.getName());
		map.put("work_place", signRtt.getWork_place());
		map.put("dutyName", signRtt.getDuty().getDutyName());
		map.put("beginDateYear", signRtt.getBeginDateYear() + "");
		map.put("beginDateMonth", signRtt.getBeginDateMonth() + "");
		map.put("beginDateDay", signRtt.getBeginDateDay() + "");
		map.put("endDateYear", signRtt.getEndDateYear() + "");
		map.put("endDateMonth", signRtt.getEndDateMonth() + "");
		map.put("endDateDay", signRtt.getEndDateDay() + "");
		map.put("payType", signRtt.getPayType());
		map.put("pieceRatePay", signRtt.getPieceRatePay() == null ? "" : signRtt
				.getPieceRatePay().longValue() + "");
		map.put("fullAward", signRtt.getFullAward());
		map.put("baseSalary", signRtt.getBaseSalary());
		map.put("dutyAllowance", signRtt.getDutyAllowance());
		map.put("paymentDate", signRtt.getPaymentDate() + "");
		

		return map;
	}

	public ContractSign getSign() {
		return sign;
	}

	public void setSign(ContractSign sign) {
		this.sign = sign;
	}

	public List<Duty> getDuties() {
		return duties;
	}

	public void setDuties(List<Duty> duties) {
		this.duties = duties;
	}

	public String getTemplateName() {
		return templateName;
	}

	public void setTemplateName(String templateName) {
		this.templateName = templateName;
	}

	public LimitedList<ContractSignViewPojo> getViewPojos() {
		return viewPojos;
	}

	public void setViewPojos(LimitedList<ContractSignViewPojo> viewPojos) {
		this.viewPojos = viewPojos;
	}

	public Long getDutyId() {
		return dutyId;
	}

	public void setDutyId(Long dutyId) {
		this.dutyId = dutyId;
	}

	public int getMonth() {
		return month;
	}

	public void setMonth(int month) {
		this.month = month;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public EmployeeinfoWork getWork() {
		return work;
	}

	public void setWork(EmployeeinfoWork work) {
		this.work = work;
	}

	public Long getSignId() {
		return signId;
	}

	public void setSignId(Long signId) {
		this.signId = signId;
	}

	public ContractSignZz getSignZz() {
		return signZz;
	}

	public void setSignZz(ContractSignZz signZz) {
		this.signZz = signZz;
	}

	public ContractSignRt getSignRt() {
		return signRt;
	}

	public void setSignRt(ContractSignRt signRt) {
		this.signRt = signRt;
	}
	
	public ContractSignRtt getSignRtt() {
		return signRtt;
	}
	
	public void setSignRtt(ContractSignRtt signRtt) {
		this.signRtt = signRtt;
	}
}
